﻿#模拟定时调度
#目前只能模拟"每天调用"
#通过指定小时数和分钟数,
#首先计算当前时刻与第二天指定时间之间的间隔，计算出第一次执行指定程序所需时间
#然后按照每天一次的间隔进行死循环

#这里最艹蛋的就是那蛋疼的函数调用方式了！！！！！

#将依据这两个指定时间 指定下一次执行的时间,定于明天的此时刻
$startTime_hour = 3;
$startTime_minute = 29;
#还需要修改的是executeExe函数,其里面有exe程序的位置



$firstSleepTime = getFirstSleepTime $startTime_hour $startTime_minute;
Write-Host $firstSleepTime;
executeOnFirstTime $firstSleepTime;
executeOnNext;

function getFirstSleepTime ($startTime_hour,$startTime_minute)
{
    $nextExecuteTime = getNextExecuteTime $startTime_hour $startTime_minute;
    $firstSleepTime = getSleepTime $nextExecuteTime;
    return  $firstSleepTime;
}

function getNextExecuteTime ( $startTime_Hour, $startTime_Minute)
{
    $now = Get-Date;
    $tomorrow = $now.AddDays(1);
    $tomorrowExeTime = New-Object -TypeName System.DateTime -ArgumentList $tomorrow.Year,$tomorrow.Month,$tomorrow.Day ;
    $result = $tomorrowExeTime.AddHours($startTime_Hour);
    $result = $result.AddMinutes($startTime_Minute);
    return    $result;
}

function getSleepTime ($nextExecuteTime)
{
    $now = Get-Date;
    $timeSpan = $nextExecuteTime - $now;
    return $timeSpan.TotalSeconds;
}

function executeOnFirstTime ($firstSleepTime)
{
    Start-Sleep $firstSleepTime;
    executeExe;
}

function executeOnNext ()
{
    $a = 1; #制造无穷循环
    while ( $a -eq 1)
    {
        $timeNeedWait = getSecondsOfOneDay;
        Start-Sleep $timeNeedWait;
        executeExe;
    }
}

function getSecondsOfOneDay ()
  {
      return 24 * 60 * 60;
  }
  
function executeExe()
{
    cd "C:\ServerDeploy\RealtimeStreamStatisticsOptimizeMemory\dist\RealtimeStreamStatisticsOptimizeMemory";
    cmd /c start "RealtimeStreamStatisticsOptimizeMemory.exe";
}






